package com.imu.purse.api.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.imu.purse.modules.app.entity.ImuUserEntity;
import com.imu.purse.modules.app.service.ImuUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.PageInfo;
import com.xiaoleilu.hutool.util.BeanUtil;
import com.xiaoleilu.hutool.util.StrUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import com.imu.common.validator.ValidatorUtils;
import com.imu.common.validator.group.AddGroup;
import com.imu.common.validator.group.UpdateGroup;
import com.imu.common.annotation.IgnoreAuth;
import com.imu.common.annotation.SysLog;
import com.imu.common.exception.ErrorDesc;
import com.imu.common.exception.ErrorUtil;
import com.imu.purse.config.PhoneValidate;
import com.imu.purse.modules.app.entity.UserCheckEntity;
import com.imu.purse.modules.app.form.CkeckForms;
import com.imu.purse.modules.app.service.UserCheckService;
import com.imu.purse.modules.sms.SMSCache;
import com.imu.purse.modules.sms.SMSMessage.Type;
import com.imu.security.SessionObject;
import com.imu.common.utils.R;

@RestController
@RequestMapping("/api")
@Api(tags="用户验证接口")
public class UserCheckController
{
	
	/****
	 * 新增
 	 * @date 2018-07-19 14:30:09
	 * @return
	 */
	@IgnoreAuth
	@PostMapping("/saveUserCheck")
	@ApiOperation("新增")
	public R save(HttpServletRequest request,@RequestHeader("X-IMU-SECRET") String secret, 
			@RequestHeader("X-IMU-SESSION") String token,@RequestBody CkeckForms form)
	{
		ValidatorUtils.validateEntity(form, AddGroup.class);
		String uid = com.imu.security.SessionTokenProviderFactory.getSessionTokenProvider().getUserId(secret, token);
	    if(StrUtil.isEmpty(uid)){
	       return ErrorUtil.errorMesg(request,ErrorDesc.TOKEN_EMPTY);
	    }
		//验证手机验证码
        String type = String.valueOf(form.getType());
        Type messageType = PhoneValidate.Authentication(type);
        if(messageType == null){
        	return ErrorUtil.errorMesg(request,ErrorDesc.TYPE_ERR);
        }
        if(!StringUtils.isNotEmpty(form.getImei())){
        	return ErrorUtil.errorMesg(request,ErrorDesc.IME_EMPTY);
        }
		//判断是否有该用户
		ImuUserEntity imuUser = imuUserService.queryByMobile(form.getPhone());
		if(imuUser == null){
			return ErrorUtil.errorMesg(request,ErrorDesc.PHONE_ERR);
		}
		String picPass = form.getPicPass().toLowerCase();
		if(StrUtil.isEmpty(redisTemplate.opsForValue().get(picPass))){
			return ErrorUtil.errorMesg(request,ErrorDesc.PHOTO_ACODE_ERROR);
		}
		String phone = StrUtil.isEmpty(imuUser.getInterPhone()) ? form.getPhone() : imuUser.getInterPhone();
        String a = cache.findCode(messageType.getType(), phone);
        if(StringUtils.isNotEmpty(a)){
            if(!a.equals(form.getCode())){
                return ErrorUtil.errorMesg(request,ErrorDesc.ACODE_ERROR);
            }
        }else {
            return ErrorUtil.errorMesg(request,ErrorDesc.ACODE_ERROR);
        }
		UserCheckEntity et =new UserCheckEntity();
		et.setCheckType(form.getCheckType());
		et.setCheckValue(form.getCheckValue());
		et.setImei(form.getImei());
		et.setUserId(Long.valueOf(uid));
		et.setTimeCreate(new Date());
		service.save(et);

		//删除图片验证码和短信验证码
		//删除图片验证码
		redisTemplate.delete(picPass);
		//删除手机验证码
		cache.delCode(type,phone);
		return R.ok(1);
	}


	/**
	 * 提供给接口调用
	 * @param dto
	 * @return
	 */
	@IgnoreAuth
	@GetMapping("/checkPwd")
	public R checkPwd(@RequestParam String phone, @RequestParam String pwd)
	{
		if(!StringUtils.isNotEmpty(phone)){
			return R.error(ErrorDesc.PHONE_EMPTY.getCode(), ErrorDesc.PHONE_EMPTY.getMsg());
		}
		if(!StringUtils.isNotEmpty(pwd)){
			return R.error(ErrorDesc.PWD_EMPTY.getCode(), ErrorDesc.PWD_EMPTY.getMsg());
		}
		ImuUserEntity imuUser=imuUserService.queryByMobile(phone);
		if(imuUser==null){
			return R.error(ErrorDesc.USER_UEXIST.getCode(), ErrorDesc.USER_UEXIST.getMsg());
		}
		if(!imuUser.getPwd().equals(new Sha256Hash(pwd, imuUser.getSalt()).toHex())){
			return R.error(ErrorDesc.PHONE_OR_PWD_REG.getCode(), ErrorDesc.PHONE_OR_PWD_REG.getMsg());
		}
		return R.ok(1);
	}

	@Autowired
	private UserCheckService service;
	
	@Autowired
    private SMSCache cache;

	@Autowired
	private ImuUserService imuUserService;

	@Autowired
	private RedisTemplate<String,String> redisTemplate;
}
